package com.example.social.viewmodel

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.social.api.ApiClient.userApiService
import com.example.social.api.BaseResponse
import com.example.social.api.UserList
import com.example.social.model.ThreadModel
import com.example.social.model.UserModel

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response


class SearchViewModel : ViewModel() {

    private val _users = MutableLiveData<List<UserList>>()
    val userList: LiveData<List<UserList>> = _users


    init {
        fetchUsers {
            _users.value = it
        }
    }


    private fun fetchUsers(onResult: (List<UserList>) -> Unit) {
        //TODO:获取用户列表
        val call = userApiService.getUserList()
        call.enqueue(object:Callback<BaseResponse<List<UserList>>>{
            override fun onResponse(
                call: Call<BaseResponse<List<UserList>>>,
                response: Response<BaseResponse<List<UserList>>>
            ) {
                if (response.isSuccessful) {
                    val result = response.body();
                    if(result?.code==0){
                        onResult(result.data)
                    }else{
                        Log.e("fetchUsers", "数据为空.")
                    }
                }
            }

            override fun onFailure(call: Call<BaseResponse<List<UserList>>>, t: Throwable) {
                Log.e("fetchUsers", "请求失败", t)
            }


        })
    }

    fun fetchUserFromThread(thread: ThreadModel, onResult: (UserModel) -> Unit) {

    }
}